package com.example.verifysdk.scancode;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.verifysdk.LogUtil;
import com.example.verifysdk.R;
import com.example.verifysdk.SpHelper;
import com.example.verifysdk.scancode.google.zxing.integration.android.IntentIntegrator;
import com.example.verifysdk.scancode.google.zxing.integration.android.IntentResult;

/**
 * @author liuv
 */
public class ShowQRInfoActivity extends Activity implements ShowQRInfoPresenter.ShowQRInfoView {
    private static final String TAG = "ShowQRInfoActivity";

    private static final int VERIFY_SCCESS = 0; //验证通过
    private static final int QRCODE_IS_CONNOT_USE = 108;  //二维码不可用
    private static final int QRCODE_IS_OUT_TIME = 109;  //二维码过期
    private static final int QRCODE_OFFLINE_NUMBER_OUT = 110;   //离线码使用次数过限

    private ImageView mBackIv;
    private TextView mTitleTv;
    private ImageView mResultIv;
    private TextView mResultTv;
    private TextView mResultInfoTv;
    private Button mScanAgainBtn;

    private Bundle mBundle;
    private String mAppPartner;
    private String mAppPartnerRemark;
    private ShowQRInfoPresenter mShowQRInfoPresenter;
    private SpHelper mSpHelper;
    private String mSecret;
    private Intent mIntent;
    private String mIdentity = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_qrinfo);
        initView();
        initData();
    }

    private void initView() {
        mBackIv = (ImageView) findViewById(R.id.top_bar_back_iv);
        mTitleTv = (TextView) findViewById(R.id.top_bar_title_tv);
        mResultIv = (ImageView) findViewById(R.id.show_qrinfo_result_iv);
        mResultTv = (TextView) findViewById(R.id.show_qrinfo_result_tv);
        mResultInfoTv = (TextView) findViewById(R.id.show_qrinfo_result_info_tv);
        mScanAgainBtn = (Button) findViewById(R.id.show_qrinfo_scan_again_btn);

        mBackIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setBackInfo();
            }
        });
        mTitleTv.setText("验证结果");
        mScanAgainBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scanCode();
            }
        });
    }

    private void initData() {
        mIntent = getIntent();
        mBundle = getIntent().getExtras();
        if (mBundle != null) {
            mAppPartner = mBundle.getString("partnerId");
            mAppPartnerRemark = mBundle.getString("userId");
        }

        if (TextUtils.isEmpty(mAppPartner) || TextUtils.isEmpty(mAppPartnerRemark)) {
            showToast("参数错误", 0);
            finish();
        }

        mShowQRInfoPresenter = new ShowQRInfoPresenter();
        mShowQRInfoPresenter.setmShowQRInfoView(this);

        mSpHelper = new SpHelper(this);
        mSpHelper.putPartenrRemark(mAppPartnerRemark);

        scanCode();
    }

    private void scanCode() {
        IntentIntegrator intentIntegrator = new IntentIntegrator(this);
        intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
        intentIntegrator.initiateScan();

        clearResult();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                Toast.makeText(this, "已取消", Toast.LENGTH_LONG).show();
                finish();
            } else {
//                Toast.makeText(this, "" + result.getContents(), Toast.LENGTH_LONG).show();
                mSecret = result.getContents();
                if (mSecret.contains(":") || mSecret.contains(".")){
                    showResultNo("二维码不合法", mSecret);
                    return;
                }
                if (TextUtils.isEmpty(mSpHelper.getScannerToken())) {
                    mShowQRInfoPresenter.loginScanUser(mAppPartner, mAppPartnerRemark);
                } else {
                    checkSec();
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void checkSec() {
        mShowQRInfoPresenter.checkSecret(mSpHelper.getScannerToken(), mSecret);
    }

    private void showResultYes(final String title, final String info) {
        LogUtil.i(TAG, "---info===" + info);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mResultIv.setImageResource(R.mipmap.result_yes);
                mResultTv.setText(title);
                mResultInfoTv.setText(info);
            }
        });
    }

    private void showResultNo(final String title, final String info) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mResultIv.setImageResource(R.mipmap.result_no);
                mResultTv.setText(title);
                mResultInfoTv.setText(info);
            }
        });
    }

    private void clearResult() {
        mResultIv.setImageResource(0);
        mResultTv.setText("");
        mResultInfoTv.setText("");
    }

    private void showToast(final String toast, final int showMode) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(ShowQRInfoActivity.this, toast, showMode).show();
            }
        });
    }

    @Override
    public void onBackPressed() {
        setBackInfo();
    }

    private void setBackInfo(){
        mIntent.putExtra("identity", mIdentity);
        setResult(0, mIntent);
        finish();
    }

    @Override
    public void loginSuccess(String token) {
        mSpHelper.setScannerToken(token);
        checkSec();
    }

    @Override
    public void loginFail(Exception e) {
        showToast(e.getMessage(), 0);
        if (e.getMessage().equals("服务器响应异常")) {
            finish();
        }
    }

    @Override
    public void checkSuccess(String info) {
        showResultYes("验证通过", info);
    }

    @Override
    public void checkFail(Exception e) {
//        showToast(e.getMessage(), 0);
        showResultNo(e.getMessage(), "");
    }

    @Override
    public void mustRelogin() {
        mShowQRInfoPresenter.loginScanUser(mAppPartner, mAppPartnerRemark);
    }

    @Override
    public void sendId(String id) {
        mIdentity = id;
    }

    @Override
    public Context getViewContext() {
        return this;
    }


}
